package com.genreate.util.jtk;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aliyun.dingtalkconference_1_0.models.CreateVideoConferenceResponse;
import com.aliyun.dingtalkconference_1_0.models.CreateVideoConferenceResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.genreate.constant.ServiceException;
import com.genreate.util.jtk.reqRes.*;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 钉钉接口列表对接实现类
 *
 * @author LYS
 * @date 2025-01-14
 */
public class DingdingUtil {
    @Autowired
//    private RedisService redisService;
    /**
     * 钉钉企业ID
     */
    private static String corpId = "ding61bdb62c9797ae404ac5d6980864d335";
    /**
     * 钉钉应用ID
     */
    private static String appId = "a01edfcc-b4c9-4369-8c8c-a3fe85a7a8e6";
    /**
     * 钉钉应用AgentId
     */
    private static String agentId = "3360271081";
    /**
     * 钉钉开放平台应用client_id (原 AppKey 和 SuiteKey)
     */
    private static String client_id = "ding9cdpei685h6ptcqo";
    /**
     * 钉钉开放平台应用client_secret (原 AppSecret 和 SuiteSecret)
     */
    private static String client_secret = "pSEcIx3Ko-0G5MhMbetGjxMWzIYXI6hIhcsIug97enSaVSCLzcp6KZsIAXKJTr94";
    /**
     * 钉钉机器人code
     */
    private static String robot_code = "ding9cdpei685h6ptcqo";

    /**
     * 获取钉钉令牌
     *
     * @return {@link String }
     */

    public String getDingdingToken() {
//        String accessToken = redisService.getCacheObject(RedisKeyNameUtil.getDingdingAccessTokenKey());
//        if(StrUtil.isNotBlank(accessToken)){
//            return accessToken;
//        }
        String accessToken = "";
        String apiUrl = StrUtil.format("https://oapi.dingtalk.com/gettoken?appkey={}&appsecret={}", client_id, client_secret);
        try {
            String data = HttpUtil.get(apiUrl);
            JSONObject jsonRel = JSONUtil.parseObj(data);
            if (jsonRel.getInt("errcode") == 0 && "ok".equals(jsonRel.getStr("errmsg"))) {
                accessToken = jsonRel.getStr("access_token");
                Long expiresIn = jsonRel.getLong("expires_in");
//                redisService.setCacheObject(RedisKeyNameUtil.getDingdingAccessTokenKey(),accessToken,expiresIn, TimeUnit.SECONDS);
                return accessToken;
            } else {
                throw new ServiceException(jsonRel.getStr("errmsg"));
            }
        } catch (Exception e) {
            throw new ServiceException(String.format("%s:%s", apiUrl, e.toString()));
        }
    }

    /**
     * 通过电话获取用户信息
     *
     * @param phone 电话
     * @return {@link DingdingUserRes }
     */

    public DingdingUserRes getUserInfoByPhone(String phone) {
        String apiUrl = StrUtil.format("https://oapi.dingtalk.com/topapi/v2/user/getbymobile?access_token={}", getDingdingToken());
        Dict parameters = Dict.create().set("mobile", phone).set("support_exclusive_account_search", true);
        String body = JSONUtil.toJsonStr(parameters);
        try {
            String data = HttpRequest.post(apiUrl).body(body)
                    .execute().body();
            JSONObject jsonRel = JSONUtil.parseObj(data);
            if (jsonRel.getInt("errcode") == 0 && "ok".equals(jsonRel.getStr("errmsg"))) {
                DingdingUserRes result = JSONUtil.toBean(jsonRel.getStr("result"), DingdingUserRes.class);
                return result;
            } else {
                throw new ServiceException(jsonRel.getStr("errmsg"));
            }
        } catch (Exception e) {
            throw new ServiceException(String.format("%s:%s", apiUrl, e.toString()));
        }
    }

    /**
     * 获取unionid
     *
     * @param userid 用户id
     * @return {@link DingdingUserRes }
     */

    public DingdingUnionInfoRes getUnion(String userid) {
        String apiUrl = StrUtil.format("https://oapi.dingtalk.com/topapi/v2/user/get?access_token={}", getDingdingToken());
        Dict parameters = Dict.create().set("userid", userid);
        String body = JSONUtil.toJsonStr(parameters);
        try {
            String data = HttpRequest.post(apiUrl).body(body)
                    .execute().body();
            JSONObject jsonRel = JSONUtil.parseObj(data);
            if (jsonRel.getInt("errcode") == 0 && "ok".equals(jsonRel.getStr("errmsg"))) {
                DingdingUnionInfoRes result = JSONUtil.toBean(jsonRel.getStr("result"), DingdingUnionInfoRes.class);
                return result;
            } else {
                throw new ServiceException(jsonRel.getStr("errmsg"));
            }
        } catch (Exception e) {
            throw new ServiceException(String.format("%s:%s", apiUrl, e.toString()));
        }
    }

    /**
     * 创建群聊
     *
     * @param dingdingCreateGroupReq 钉钉创建群要求
     * @return {@link DingdingCreateGroupRes }
     */
    public DingdingCreateGroupRes createGroup(DingdingCreateGroupReq dingdingCreateGroupReq) {
        Opt.ofNullable(dingdingCreateGroupReq).orElseThrow(() -> new ServiceException("创建群聊参数为空"));
        String name = dingdingCreateGroupReq.getName();
        if (StrUtil.isBlank(name)) {
            throw new ServiceException("群聊名称不能为空");
        }
        if (name.length() > 20) {
            throw new ServiceException("群聊名称长度不能超过20");
        }
        //一下参数设置为默认值
        dingdingCreateGroupReq.setShowHistoryType(1);
        dingdingCreateGroupReq.setSearchable(0);
        dingdingCreateGroupReq.setValidationType(0);
        dingdingCreateGroupReq.setMentionAllAuthority(0);
        dingdingCreateGroupReq.setManagementType(0);
        dingdingCreateGroupReq.setChatBannedType(0);
        String apiUrl = StrUtil.format("https://oapi.dingtalk.com/chat/create?access_token={}", getDingdingToken());
        String body = JSONUtil.toJsonStr(dingdingCreateGroupReq);
        try {
            String data = HttpRequest.post(apiUrl).body(body)
                    .execute().body();
            JSONObject jsonRel = JSONUtil.parseObj(data);
            if (jsonRel.getInt("errcode") == 0 && "ok".equals(jsonRel.getStr("errmsg"))) {
                DingdingCreateGroupRes result = JSONUtil.toBean(data, DingdingCreateGroupRes.class);
                return result;
            } else {
                throw new ServiceException(jsonRel.getStr("errmsg"));
            }
        } catch (Exception e) {
            throw new ServiceException(String.format("%s:%s", apiUrl, e.toString()));
        }
    }

    /**
     * 更新群聊
     *
     * @param dingdingCreateGroupReq 钉钉创建群要求
     */
    public void updateGroup(DingdingCreateGroupReq dingdingCreateGroupReq) {
        Opt.ofNullable(dingdingCreateGroupReq).orElseThrow(() -> new ServiceException("更新群聊参数为空"));
        dingdingCreateGroupReq.setIsBan(false);
        String apiUrl = StrUtil.format("https://oapi.dingtalk.com/chat/update?access_token={}", getDingdingToken());
        String body = JSONUtil.toJsonStr(dingdingCreateGroupReq);
        try {
            String data = HttpRequest.post(apiUrl).body(body)
                    .execute().body();
            JSONObject jsonRel = JSONUtil.parseObj(data);
            if (jsonRel.getInt("errcode") != 0 && !"ok".equals(jsonRel.getStr("errmsg"))) {
                throw new ServiceException(jsonRel.getStr("errmsg"));
            }
        } catch (Exception e) {
            throw new ServiceException(String.format("%s:%s", apiUrl, e.toString()));
        }
    }

    /**
     * 使用 Token 初始化账号Client
     *
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dingtalkconference_1_0.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkconference_1_0.Client(config);
    }

    /**
     * 创建会议
     *
     * @throws Exception 例外
     */
    public DingdingCreateMeetingRes createMeeting(DingdingCreateMeetingReq dingdingCreateMeetingReq) {
        Opt.ofNullable(dingdingCreateMeetingReq).orElseThrow(() -> new ServiceException("创建群聊参数为空"));
        String confTitle = dingdingCreateMeetingReq.getConfTitle();
        if (StrUtil.isBlank(confTitle)) {
            throw new ServiceException("会议名称不能为空");
        }
        if (confTitle.length() > 50) {
            throw new ServiceException("会议名称长度不能超过50");
        }
        try {
            com.aliyun.dingtalkconference_1_0.Client client = createClient();
            com.aliyun.dingtalkconference_1_0.models.CreateVideoConferenceHeaders createVideoConferenceHeaders = new com.aliyun.dingtalkconference_1_0.models.CreateVideoConferenceHeaders();
            createVideoConferenceHeaders.xAcsDingtalkAccessToken = getDingdingToken();
            com.aliyun.dingtalkconference_1_0.models.CreateVideoConferenceRequest createVideoConferenceRequest = new com.aliyun.dingtalkconference_1_0.models.CreateVideoConferenceRequest()
                    .setUserId(dingdingCreateMeetingReq.getUserId())
                    .setConfTitle(confTitle)
                    .setInviteUserIds(dingdingCreateMeetingReq.getInviteUserIds())
                    .setInviteCaller(true);

            CreateVideoConferenceResponse videoConferenceWithOptions = client.createVideoConferenceWithOptions(createVideoConferenceRequest, createVideoConferenceHeaders, new RuntimeOptions());
            CreateVideoConferenceResponseBody body = videoConferenceWithOptions.getBody();
            DingdingCreateMeetingRes result = BeanUtil.toBean(body, DingdingCreateMeetingRes.class);
            return result;
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                throw new ServiceException(StrUtil.format("创建会议出错:{}", err.getMessage()));
            }
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                throw new ServiceException(StrUtil.format("创建会议出错:{}", err.getMessage()));
            }
        }
        return null;
    }
}
